package com.qingcheng.timer;

import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Welcome to the most Amazing IntelliJ IIIDEA.
 * Creat0r: ^_^ fffantianxing ^_^
 * Date: 2019-07-23
 * Time: 19:04
 */
@Component
public class SeckillGoodsPushTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Scheduled(cron = "0/60 * * * * ?")
    public void loadGoodsToRedis() {

        //获取时间段的集合
        List<Date> dateList = DateUtil.getDateMenus();

        //循环遍历时间段，将不同时间段的商品添加到缓存中
        for (Date startTime : dateList) {

            //获取秒杀开始时间的字符串
            String startString = DateUtil.date2Str(startTime);

            //设置查询参数
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andGreaterThanOrEqualTo("startTime",startTime); //当前时间大于开始时间
            criteria.andLessThan("endTime",DateUtil.addDateHour(startTime,2)); //结束时间不超过2小时
            criteria.andEqualTo("status", "1");//订单为已审核状态
            criteria.andGreaterThan("stockCount", "0");//库存大于0

            //排除掉之前已经添加到缓存中的商品
            Set keys = redisTemplate.boundHashOps("seckillGoods" + startString).keys();
            if (keys!=null&&keys.size()>0){
                criteria.andNotIn("id",keys);
            }

            //查询数据
            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectByExample(example);

            //根据时间段和商品id将商品添加到缓存
            for (SeckillGoods seckillGoods : seckillGoodsList) {
                redisTemplate.boundHashOps("seckillGoods" + startString).put(seckillGoods.getId(), seckillGoods);
                redisTemplate.boundHashOps("seckillGoods" + startString).expire(2, TimeUnit.HOURS);
            }

        }
    }
}
